using UnityEngine;
using System.Collections;


public class InterfaceCreator {
	
	private static TextMesh text3d;
    private static GameObject _anchorLeftUp;
    private static GameObject _anchorLeftDown;
    private static GameObject _anchorRightDown;
    private static GameObject _anchorRightUp;
    private static float _totalWidth;
    private static float _totalHeight;
	
	private static Camera _cam;
	private static Transform _parent;
	
	public static void SetParameters(Camera cam, Transform parent)
	{
		_cam = cam;	
		_parent = parent;
	}
	
	static void PlaceAnchors()
	{
		//Place Anchors
        Utils.PlaceHUDAnchors(_cam, _parent, out _anchorLeftUp, out _anchorLeftDown, out _anchorRightUp, out _anchorRightDown);
        _totalWidth = _anchorRightDown.transform.localPosition.x - _anchorLeftDown.transform.localPosition.x;
        _totalHeight = _anchorRightUp.transform.localPosition.y - _anchorRightDown.transform.localPosition.y;	
	}
	
	
	//Deserialize & Create Text mesh
	public static Transform DeserializeText(XMLInStream stream, Transform parent)
	{
		string name;
		Vector3 pos;
		float height;
		string snap = "";
		
        stream.Attribute("name", out name);
		stream.Content("position", out pos);
		stream.Content("height", out height);
		stream.ContentOptional("snap", ref snap);

		return CreateText(name, parent, pos, height, snap);
	}
	
	//Create Text Mesh
	public static Transform CreateText(string name, Transform parent, Vector3 position, float heightPercent, string snap = "leftDown")
    {
		if(_anchorLeftUp == null)
		{
			PlaceAnchors();	
		}
		
		if(text3d == null)
		{
			text3d = (Resources.Load("Prefabs/3DText") as GameObject).GetComponent<TextMesh>();
		}
		
        //Get Position        
        position = GetPosition(position, snap);

        TextMesh text = GameObject.Instantiate(text3d, position, Quaternion.identity) as TextMesh;
        text.transform.parent = _parent;
        text.transform.localPosition = position;

        text.gameObject.transform.parent = parent;
        //text.transform.position = position;
        text.fontSize = (int)(heightPercent * GameSetting.getInstance().screenResolution.x / 1280.0f);
        text.text = "0";
        //text.gameObject.layer = Const.LAYERHUD;
        text.name = name;

        return text.transform;
    }
	
	//Deserialize & Create Button
	public static Transform DeserializeButton(XMLInStream stream, Transform parent)
	{
		string name;
        Vector3 pos;
        float height;
        string snap = "";

		stream.Attribute("name", out name);
        stream.Content("position", out pos);
        stream.Content("height", out height);
        stream.ContentOptional("snap", ref snap);

        return CreateButton(name, parent, pos, height, true, snap);
		
	}
	
    //Create Button
    public static Transform CreateButton(string name, Transform parent, Vector3 position, float heightPercent, bool trueValue = true, string snap = "leftDown")
    {
		if(_anchorLeftUp == null)
		{
			PlaceAnchors();	
		}
		
        //Get Texture
        ButtonTexture buttonTexture = TextureManager.Instance().GetButtonTexture(name);

        bool baseButton = false;
        string nameBaseButton = "";
        if (buttonTexture.baseButton != "")
        {
            nameBaseButton = buttonTexture.baseButton;
            buttonTexture = TextureManager.Instance().GetButtonTexture(buttonTexture.baseButton);
            baseButton = true;

        }

        Texture texture = buttonTexture.GetTexture(ButtonTexture.StateButton.NORMAL);

        //Get Position        
        Vector3 newPos = GetPosition(position, snap);

        //Get Height & Width
        float height = 0;
        float width = 0;
        if (!trueValue)
        {
            height = (heightPercent * (parent.collider.bounds.size.y)) / 100;
            float rapport = texture.height / (float)texture.width;
            width = (height / rapport) / buttonTexture.GetNbTexture(ButtonTexture.StateButton.NORMAL);
        }
        else
        {
            height = texture.height * _totalHeight / Const.TEXTURE_BASE_RESOLTION.y;
            float rapport = texture.height / (float)texture.width;
            width = (height / rapport);
        }

        //Create Plane & apply Texture
        Transform plane = CreatePlane(newPos, width, height, parent);
        plane.renderer.material = new Material(Shader.Find("Transparent/Diffuse"));
        plane.renderer.material.mainTexture = texture;

        plane.gameObject.layer = Const.LAYER_HUD;
        plane.name = name;
        plane.gameObject.AddComponent<HUDButton>();
        plane.gameObject.GetComponent<HUDButton>().SetName(name, ButtonTexture.StateButton.NORMAL, nameBaseButton);

        if (baseButton)
        {
			//Text
			if(TextureManager.Instance().GetTexture(name) == null)
			{
				Transform textPanel = CreateText(name, plane.transform, position, 80);
				textPanel.localPosition = new Vector3(0, 0, 0);
				textPanel.GetComponent<TextMesh>().anchor = TextAnchor.MiddleCenter;
                textPanel.GetComponent<TextMesh>().text = TextManager.Instance().GetText(name);
			}
			//Texture
			else
			{
				Transform texturePanel = CreateTexturePanel(name, plane.transform, position, 0, true, "parent", true);
            	texturePanel.collider.enabled = false;
			}
            
        }


        return plane;
    }

    //Place Panel SubPart
    public static Transform CreatePanelSub(string name, Transform parent, Vector3 position, float heightPercent, float widthPercent, string snap = "leftDown")
    {
		if(_anchorLeftUp == null)
		{
			PlaceAnchors();	
		}
		
        //Get Position        
        position = GetPosition(position, snap);

        //Get Height & Width
        //float height = (heightPercent * (parent.collider.bounds.size.y)) / 100;
        //float width = (widthPercent * (parent.collider.bounds.size.x)) / 100;

        //Create Plane & apply Texture
        //Transform plane = CreatePlane(position, width, height, parent);
        //plane.renderer.enabled = false;
        //plane.collider.enabled = false;
        //plane.gameObject.layer = Const.LAYERHUD;
        //plane.name = name;
        Transform plane = new GameObject().transform;
        plane.transform.position = parent.position;
        plane.parent = parent;
        plane.name = name;
        plane.gameObject.layer = Const.LAYER_HUD;
        return plane;
    }
	
	//Deserialize & Create Texture panel
	public static Transform DeserializeTexture(XMLInStream stream, Transform parent)
	{
		string name;
        Vector3 pos;
        float height;
        string snap = "";
		
		stream.Attribute("name", out name);
        stream.Content("position", out pos);
        stream.Content("height", out height);
        stream.ContentOptional("snap", ref snap);

        return CreateTexturePanel(name, parent, pos, height, true, snap);	
	}
	
    //Create Texture Panel
    public static Transform CreateTexturePanel(string name, Transform parent, Vector3 position, float heightPercent, bool trueValue = true, string snap = "leftDown", bool snapParent = false)
    {
		if(_anchorLeftUp == null)
		{
			PlaceAnchors();	
		}
		
        //Get Texture
        Texture texture = TextureManager.Instance().GetTexture(name);

        //Get Position        
        position = GetPosition(position, snap, parent);

        //Get Height & Width
        float height;
        float width;
        if (!trueValue)
        {
            height = (heightPercent * (_anchorRightUp.transform.localPosition.y - _anchorRightDown.transform.localPosition.y)) / 100;
            float rapport = texture.height / (float)texture.width;
            width = (height / rapport);
        }
        else
        {

            height = texture.height * _totalHeight / Const.TEXTURE_BASE_RESOLTION.y;
            float rapport = texture.height / (float)texture.width;
            width = (height / rapport);

        }




        //Create Plane & apply Texture
        Transform plane = CreatePlane(position, width, height, parent);
        plane.renderer.material = new Material(Shader.Find("Transparent/Diffuse"));
        plane.renderer.material.mainTexture = texture;

        plane.gameObject.layer = Const.LAYER_HUD;
        plane.name = name;

        if (snapParent)
        {
            plane.localPosition = new Vector3(0, 0, parent.localPosition.z - 1);
        }

        return plane;
    }

    //Place Panel
    public static Transform CreateHUDPanel(string name, Vector3 position, float heightPercent, string nameTexture = "", string snap = "leftDown", bool trueValue = false)
    {
		if(_anchorLeftUp == null)
		{
			PlaceAnchors();	
		}
		
        //Get Texture
        Texture texture = TextureManager.Instance().GetTexture(nameTexture);

        //Get Start Pos
        position = GetPosition(position, snap);

        //Get Height & Width
        float height;
        float width;
        if (!trueValue)
        {
            height = (heightPercent * (_anchorRightUp.transform.position.y - _anchorRightDown.transform.position.y)) / 100.0f;
            float rapport = texture.height / (float)texture.width;
            width = (height / rapport);
        }
        else
        {
            height = texture.height * _totalHeight / Const.TEXTURE_BASE_RESOLTION.y;
            float rapport = texture.height / (float)texture.width;
            width = (height / rapport);

        }

        //Create Plane & apply Texture
        Transform plane = CreatePlane(position, width, height, _parent);
        plane.renderer.material = new Material(Shader.Find("Transparent/Diffuse"));
        plane.renderer.material.mainTexture = texture;
        plane.gameObject.layer = Const.LAYER_HUD;
        plane.name = name;

        return plane;
    }

    //Get Position
    static Vector3 GetPosition(Vector3 position, string snap, Transform parent = null)
    {
        //Get Start Pos
        Vector3 startPos = Vector3.zero;

        if (snap == "")
            snap = "leftDown";

        if (snap == "leftUp")
        {
            startPos = _anchorLeftUp.transform.localPosition;
        }
        else if (snap == "rightUp")
        {
            startPos = _anchorRightUp.transform.localPosition;
        }
        else if (snap == "rightDown")
        {
            startPos = _anchorRightDown.transform.localPosition;
        }
        else if (snap == "leftDown")
        {
            startPos = _anchorLeftDown.transform.localPosition;
        }
        else if (snap == "parent")
        {
            startPos = parent.localPosition;
            return startPos;
        }


        startPos += new Vector3(position.x * _totalWidth / 100.0f, position.y * _totalHeight / 100.0f, position.z);

        return startPos;
    }


    //Create a plane with Left Down Corner, width height & parent
    public static Transform CreatePlane(Vector3 leftDown, float width, float height, Transform parent)
    {
        Transform t = new GameObject().transform;


        //t.position = parent.position;


        //Add Mesh Filter
        if (t.GetComponent<MeshFilter>() == null)
            t.gameObject.AddComponent<MeshFilter>();

        //Add Mesh Renderer
        if (t.GetComponent<MeshRenderer>() == null)
            t.gameObject.AddComponent<MeshRenderer>();

        MeshFilter filter = t.GetComponent<MeshFilter>();

        //Place Vertices
        Mesh rectangleMesh = new Mesh();
        /*
        rectangleMesh.vertices = new Vector3[] {
            new Vector3(leftDown.x, leftDown.y, leftDown.z),
            new Vector3(leftDown.x, leftDown.y + height, leftDown.z),
            new Vector3(leftDown.x + width, leftDown.y + height, leftDown.z),
            new Vector3(leftDown.x + width, leftDown.y, leftDown.z),
        };
         */
        rectangleMesh.vertices = new Vector3[] {
            new Vector3(- width / 2.0f, - height / 2.0f, 0),
            new Vector3(- width / 2.0f, height / 2.0f, 0),
            new Vector3(width / 2.0f, height / 2.0f, 0),
            new Vector3(width / 2.0f, - height / 2.0f, 0),
        };
        t.position = _parent.position + new Vector3(leftDown.x + width / 2.0f, leftDown.y + height / 2.0f, leftDown.z);
        t.parent = parent;

        rectangleMesh.SetTriangles(
            new int[]
            {
                0, 1, 3,
                1, 2, 3,
            }, 0);


        rectangleMesh.uv =
            new Vector2[]
            {
                new Vector2(0, 0),
                new Vector2(0, 1),
                new Vector2(1, 1),
                new Vector2(1, 0),
            };

        rectangleMesh.normals =
            new Vector3[]
            {
                new Vector3(0, 1, 0),
                new Vector3(0, 1, 0),
                new Vector3(0, 1, 0),
                new Vector3(0, 1, 0),
            };

        filter.sharedMesh = rectangleMesh;

        //Add Collider
        t.gameObject.AddComponent<BoxCollider>();

        return t;
    }
}
